package com.hunter.api.help;

import javax.servlet.http.HttpServletRequest;

import com.alibaba.fastjson.JSONObject;

import com.auth0.jwt.JWT;
import com.hunter.api.bean.UserBean;
import com.hunter.api.help.result.ErrorHelp;
import com.hunter.api.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class UserHelper {
    @Autowired
    private UserMapper userMapper;

    public JSONObject getUserInfo(HttpServletRequest httpServletRequest, JSONObject data) {
        JSONObject json = new JSONObject();
        String token = httpServletRequest.getHeader("token");
        Long userId = Long.valueOf(JWT.decode(token).getAudience().get(0));
        if (userId != null) {
            UserBean user = this.userMapper.userInfo(userId);
            if (user != null) {
                String username = user.getUsername();
                String name = user.getName();
                Long id = user.getId();
                Long org_id = user.getOrg_id();
                if (data == null) {
                    data = new JSONObject();
                }
                if (id != null) {
                    data.put("u.user_id", id);
                }
                if (name != null) {
                    data.put("u.name", name);
                }
                if (username != null) {
                    data.put("u.username", username);
                }
                if (org_id != null) {
                    data.put("u.org_id", org_id);
                }
                return data;
            }
            json = ErrorHelp.USER_NOT_EXISTS;
            new Exception(json.toJSONString());
        } else {

            json = ErrorHelp.TOKEN_ERROR;
            new Exception(json.toJSONString());
        }
        return json;
    }
}
